package com.kucowka.store.controllers;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ProgressController {

	private Map<String, Integer> progressMap = new HashMap<String, Integer>();

	@RequestMapping(value = "/job", method = RequestMethod.GET, headers = "Accept=*/*")
	public @ResponseBody
	String startJob() {
		System.out.println("HTTP GET start job");

		String jobHash = UUID.randomUUID().toString();
		jobHash = jobHash.replaceAll("-", "");

		System.out.println("New job hash: " + jobHash);
		progressMap.put(jobHash, 0);

		return jobHash;
	}

	@RequestMapping(value = "/progress", method = RequestMethod.GET, headers = "Accept=*/*")
	public @ResponseBody String getJobProgress(@RequestParam(required = false) String hash, HttpServletResponse response, HttpServletRequest request) {

		Integer progress = progressMap.get(hash);

		if (progress != null) {
			progress += 5;
			if (progress >= 100) {
				progressMap.remove(hash);
			} else {
				progressMap.put(hash, progress);
			}
		} else {
			progress = 0;
		}
		
		response.setStatus(HttpServletResponse.SC_OK);

		return progress.toString();
	}
}
